package com.lhfeiyu.action.front.auction;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.lhfeiyu.action.common.CreditMoney;
import com.lhfeiyu.config.Const;
import com.lhfeiyu.config.Page;
import com.lhfeiyu.config.Tip;
import com.lhfeiyu.po.AuctionGoods;
import com.lhfeiyu.po.AuctionProfession;
import com.lhfeiyu.po.AuctionProfessionOffers;
import com.lhfeiyu.po.AuctionUser;
import com.lhfeiyu.po.base.BaseShop;
import com.lhfeiyu.po.base.BaseUser;
import com.lhfeiyu.po.base.BaseUserFund;
import com.lhfeiyu.service.AuctionGoodsService;
import com.lhfeiyu.service.AuctionProfessionOffersService;
import com.lhfeiyu.service.AuctionProfessionService;
import com.lhfeiyu.service.AuctionUserService;
import com.lhfeiyu.service.AuthCheckService;
import com.lhfeiyu.service.base.BaseShopService;
import com.lhfeiyu.service.base.BaseUserControlService;
import com.lhfeiyu.service.base.BaseUserFundService;
import com.lhfeiyu.service.base.BaseUserService;
import com.lhfeiyu.tools.base.ActionUtil;
import com.lhfeiyu.tools.base.Check;
import com.lhfeiyu.tools.base.CommonGenerator;
import com.lhfeiyu.tools.base.Result;
import com.lhfeiyu.util.base.RequestUtil;

@Controller
@RequestMapping(value="/ap/hall")
public class AuctionHallAction {
	@Autowired
	private AuctionProfessionService apService;
	@Autowired
	private AuctionGoodsService agService;
	@Autowired
	private AuctionUserService auService;
	@Autowired
	private BaseUserControlService userControlService;
	@Autowired
	private AuthCheckService authCheckService;
	@Autowired
	private BaseUserService userService;
	@Autowired
	private BaseUserFundService ufService;
	@Autowired
	private BaseShopService shopService;
	@Autowired
	private AuctionProfessionOffersService apoService;
	
	private static Logger logger = Logger.getLogger("R");
	
	@RequestMapping(value="/tradeDesc")
	public ModelAndView tradeDesc(HttpServletRequest request,ModelMap modelMap,@RequestParam(required=false) String r) {
		JSONObject json = new JSONObject();
		modelMap = authCheckService.checkWxLogin(request, modelMap, json, true, r);
		return new ModelAndView(Page.tradeDesc);
	}

	@RequestMapping(value="/{auctionSerial}")
	public ModelAndView professionHall(ModelMap modelMap, HttpServletRequest request
			,@PathVariable String auctionSerial
			,@RequestParam(required=false) String r) {
		String path = Page.professionHall;
		try{
			JSONObject json = new JSONObject();
			modelMap = authCheckService.checkWxLogin(request, modelMap, json, true, r);
			BaseUser user = ActionUtil.checkSession4User(request.getSession());
			Date date = new Date();
			if(null == user){
				String jumpUrl = "/ap/hall/"+auctionSerial;
				return Result.userSessionInvalid(modelMap, ActionUtil.buildPromoterUrl(jumpUrl, r));
			}
			int userId = user.getId();
			BaseUser db_user = userService.selectByPrimaryKey(userId);
			Map<String,Object> map = new HashMap<String,Object>();
			map.put("userId", userId);
			map.put("controlTypeId", 51);
			map.put("controlDate", 1);
			int userControlList = userControlService.selectCountByCondition(map);
			if(userControlList > 0){
				json.put("forbidden", 1);
				path = "/ap";
				return new ModelAndView(ActionUtil.buildPromoterUrl(path, r), modelMap);
			}
			//检查手机号码（充值时检查支付密码）
			if(Check.isNull(db_user.getPhone())){
				json.put("bindPhone", 1);//未绑定手机号码
			}
			
			//Map<String,Object> map = CommonGenerator.getHashMap();
			map.put("userId", userId);
			BaseShop shop = shopService.selectByCondition(map);
			if(null != shop){
				json.put("shop", shop);
			}
			
			map.clear();
			map = RequestUtil.getRequestParam(request);//自动获取所有参数（查询条件）
			map.put("serial", auctionSerial);//在URL路径中获取的参数不为被自动获取，需要手动存入paramMap
			AuctionProfession ap = apService.selectByCondition(map);
			if(null == ap){
				path = "/ap";
				return new ModelAndView(path, modelMap);
			}else if(null != ap.getMainStatus() &&( ap.getMainStatus() == 4 || ap.getMainStatus() == 5)){//未提交或在审核中，不能进入大厅
				path = "/ap";
				return new ModelAndView(path, modelMap);
			}
			modelMap.put("ap", ap);
			Integer auctionId = ap.getId();
			//TODO 更新拍场在线人数，同一用户只更新updated_at,通过该字段判断在线人数
		 	/*map.clear();
		 	map.put("auctionId", auctionId);
		 	map.put("auctionType", 1);//专场
		 	map.put("userId", userId);
		 	List<AuctionUser> auList = auService.selectListByCondition(map);
		 	if(Check.isNotNull(auList)){
		 		AuctionUser au = auList.get(0);
		 		au.setUpdatedAt(date);
		 		auService.updateByPrimaryKey(au);
		 	}else{
		 		AuctionUser au = new AuctionUser();
		 		au.setUpdatedAt(date);
		 		au.setAuctionId(auctionId);
		 		au.setAuctionType(1);
		 		au.setUserId(userId);
		 		au.setUsername(user.getUsername());
		 		au.setMainStatus(1);
		 		auService.insertSelective(au);
		 	}*/
		 	
			Integer hostId = ap.getUserId();
			if(null != hostId){//判断是否为主持人
				int hostUserId = hostId;
				if(hostUserId == userId){
					json.put("isHost", 1);
					map.clear();
				 	map.put("auctionId", auctionId);
				 	map.put("auctionType", 1);//专场
				 	map.put("showRecentUserCount", 1);
					int userCount = auService.selectCountByCondition(map);
					json.put("userCount", userCount);
					modelMap.put("isHost", 1);
				}
			}
			json.put("ap", ap);
			BigDecimal bailBD = ap.getBail();
			//Integer creditMoney = db_user.getCreditMargin();
			BaseUserFund uf = ufService.selectUserFundByUserId(userId);
			if(null == uf){
				return new ModelAndView("/", modelMap);
			}
			BigDecimal creditMoney = uf.getOtherFund();
			//信誉保证金:信誉保证金必须大于保证金
			if(null != bailBD && (null == creditMoney || bailBD.doubleValue() > creditMoney.doubleValue())){
				json.put("creditMoneyLack", 1);//前台提示交纳的保证金不足
				json.put("bail", bailBD.doubleValue());
				json.put("creditMoney", creditMoney);
				modelMap = CreditMoney.checkCreditMoneyForAP(ap, modelMap, json, uf, path);
			}
			
			String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss").format(date);
			//String sig = Const.generateSubSig(user.getThirdName(),user.getThirdPassword(),timeStamp);
			String sig = Const.generateSubSig(user.getSerial(), timeStamp);//应用登陆
			json.put("username", user.getUsername());
			json.put("senderId", userId);
			json.put("userTokenId", user.getThirdName());
			json.put("userTokenPswd", user.getThirdPassword());
			json.put("senderName", user.getUsername());
			json.put("senderAvatar", user.getAvatar());
			json.put("sig", sig);
			json.put("timeStamp", timeStamp);
			/*modelMap.put("receiverId",receiver.getId());
			modelMap.put("receiverTokenId", receiver.getThirdName());
			modelMap.put("reveiverName", receiver.getUsername());
			modelMap.put("reveiverAvatar", receiver.getAvatar());*/
			
			json.put("senderSerial", user.getSerial());//应用登陆对应的账号：用户序号
			
			// TODO 判断是否是推广进入,新增（auction_user）
			/*if(null != r){//有推广人
				String userSerial = user.getSerial();
				if(!r.equals(userSerial)){//推广人不是自己
					auService.addNotRepeatAuctionUser(r, user, ap);//新增推广记录，不会新增重复数据
				}
			}*/
			
			//TODO 检查用户的可用金额是否大于保证金金额
		 	BigDecimal bail = ap.getBail();
		 	if(null != bail && bail.doubleValue()>0){
		 		//UserFund uf = ufService.selectUserFundByUserId(userId);
		 		//DOTO 修改
		 		//BaseUserFund uf = new BaseUserFund();
		 		if(null != uf && null != uf.getOtherFund() && uf.getOtherFund().doubleValue() >= bail.doubleValue()){
		 			map.clear();
					map.put("auctionId", auctionId);
		 			apService.updateJoinNumAdd(map);//递增参拍人数
		 		}else{
		 			path = Page.professionGoods;//
		 			json.put("status", "bail_lack");
		 			json.put("auctionId", auctionId);
		 		}
		 	}
		 	json.put("auctionId", auctionId);
		 	modelMap.put("paramJson", json);
		}catch(Exception e){
			path = Page.error;
			Result.catchError(e, logger, this.getClass().getName()+"/ap/hall/"+auctionSerial, modelMap);
		}
		return new ModelAndView(path, modelMap);
	}
	
	@ResponseBody
	@RequestMapping(value="/getNextAuctionGoods", method=RequestMethod.POST)
	public JSONObject getNextAuctionGoods(HttpServletRequest request, @RequestParam Integer auctionId) {
		JSONObject json = new JSONObject();
		try {
			Map<String, Object> map = RequestUtil.getRequestParam(request);//自动获取所有参数（查询条件）
			
			AuctionProfession ap = apService.selectByPrimaryKey(auctionId);
			Integer haveBegun = ap.getHaveBegun();
			if(null == haveBegun)haveBegun = 1;
			json.put("haveBegun", haveBegun);
			
			map.remove("lastAuctionGoodsId");
			Integer total = agService.selectCountByCondition(map);
			map.put("status1", 1);//未进行拍卖的（仅剩XX件）
			Integer remain = agService.selectCountByCondition(map);
			map.put("status", 3);//成交的
			map.remove("status1");
			Integer deal = agService.selectCountByCondition(map);
			
			map.remove("status");
			map.put("status1",1);//未进行拍卖的
			map.put("start", 0);
			map.put("count", 1);
			map.put("orderBy", "id");
			map.put("ascOrdesc", "ASC");
			map.put("status1",1);//加载未拍卖的最近的一条
			AuctionGoods auctionGoods = agService.selectByCondition(map);
			if(null == auctionGoods){
				return Result.failure(json, Tip.msg_auction_over, Tip.code_auction_over);
			}
			Date d = auctionGoods.getRefreshTime();
			long remainSeconds = calculateRemainSeconds(d);
			/*if(null != d){
			}else{
				AuctionGoods tempAG = new AuctionGoods();
				tempAG.setId(a.getId());
				tempAG.setRefreshTime(new Date());
				agService.updateByPrimaryKeySelective(tempAG);
			}*/
			json.put("remainSeconds", remainSeconds);
			json.put("auctionGoods", auctionGoods);
			json.put("total", total);
			json.put("remain", remain);
			json.put("deal", deal);
		} catch (Exception e) {
			Result.catchError(e, logger, this.getClass().getName()+"/ap/hall/getNextAuctionGoods", json);
		}
		return Result.success(json);
	}
	
	@ResponseBody
	@RequestMapping(value="/updateAuctionGoods", method=RequestMethod.POST)
	public JSONObject updateAuctionGoods(HttpServletRequest request,
			@ModelAttribute AuctionGoods auctionGoods, 
			@RequestParam(required=false)Integer done){
		JSONObject json = new JSONObject();
		try {
			BaseUser user = ActionUtil.checkSession4User(request.getSession());//验证session中的user，存在即返回
			if(null == user){
				return Result.userSessionInvalid(json);//返回session过期的json提示
			}
			Integer userId = user.getId();
			String username = user.getUsername();
			Integer agId = auctionGoods.getId();
			Map<String,Object> map = new HashMap<String,Object>();
			map.put("userId", userId);
			map.put("controlTypeId", 54);
			map.put("controlDate", 1);
			int userControlList = userControlService.selectCountByCondition(map);
			if(userControlList > 0){
				return Result.failure(json, "您禁止进行拍卖竞价,请联系管理员解除限制", "auth_lack");
			}
			if(null == agId){
				return Result.failure(json, "该拍品已不存在", "id_null");
			}
			AuctionGoods ag = agService.selectByPrimaryKey(agId);
			if(null == ag){
				return Result.failure(json, "该拍品已不存在", "ag_null");
			}
			Integer status = ag.getMainStatus();
			if(null != status && 2 == status){
				return Result.failure(json, "该拍品已流拍", "already_done");
			}else if(null != status && 3 == status){
				json.put("username", ag.getOfferUsername());
				return Result.failure(json, "该拍品已被其他会员拍下", "already_deal");
			}
			
			Date date = new Date();
			if(null != done){//成交,流拍
				Integer offerUserId = ag.getOfferUserId();
				AuctionGoods a = new AuctionGoods();
				a.setId(agId);
				if(null != offerUserId){//已有人出价：成交
					a.setDealTime(date);
					a.setMainStatus(3);
					//通知购买人，和卖家
				}else{//没有人出价：流拍
					a.setMainStatus(2);
				}
				agService.updateByPrimaryKeySelective(a);
				return Result.success(json);
			}
			
			AuctionProfession ap = apService.selectByPrimaryKey(ag.getAuctionId());
			if(null == ap){
				return Result.failure(json, "拍卖记录为空", "ap_null");
			}
			if(null == ap.getHaveBegun() || ap.getHaveBegun() != 2 ){
				return Result.failure(json, "本场拍卖目前未处于拍卖中，无法出价", "haveBegun_invalid");
			}
			//出价
			
			auctionGoods.setUserId(null);
			auctionGoods.setAuctionId(null);
			auctionGoods.setGoodsId(null);
			auctionGoods.setGoodsSerial(null);
			auctionGoods.setPriceBegin(null);
			auctionGoods.setDeletedAt(null);
			auctionGoods.setDeletedBy(null);
			auctionGoods.setUpdatedAt(date);
			auctionGoods.setOfferUserId(userId);
			auctionGoods.setOfferUsername(username);
			auctionGoods.setUpdatedBy(username);
			auctionGoods.setRefreshTime(date);//倒计时的刷新时间
			agService.updateByPrimaryKeySelective(auctionGoods);
			//新增出价记录
			AuctionProfessionOffers apo = new AuctionProfessionOffers();
			apo.setAuctionId(ap.getId());
			apo.setAuctionGoodsId(agId);
			apo.setOfferUserId(userId);
			apo.setOfferUsername(username);
			apo.setOfferPrice(auctionGoods.getOfferPrice());
			apo.setOfferAt(date);
			apo.setSerial(CommonGenerator.getSerialByDate("apo"));
			apo.setCreatedAt(date);
			apo.setCreatedBy(username);
			apoService.insertSelective(apo);
			
			long remainSeconds = calculateRemainSeconds(date);
			json.put("remainSeconds", remainSeconds);
		}catch (Exception e) {
			Result.catchError(e, logger, this.getClass().getName()+"/ap/hall/", json);
		}
		return Result.success(json);
	}
	
	/*@ResponseBody
	@RequestMapping(value="/countDownAuctionGoods", method=RequestMethod.POST)
	public JSONObject countDownAuctionGoods(HttpServletRequest request,
			@RequestParam Integer auctionGoodsId, 
			@RequestParam(required=false)Integer finish, 
			@RequestParam(required=false)Integer countDown){
		JSONObject json = new JSONObject();
		try {
			BaseUser user = ActionUtil.checkSession4User(request.getSession());//验证session中的user，存在即返回
			if(null == user){
				return Result.userSessionInvalid(json);//返回session过期的json提示
			}
			Integer userId = user.getId();
			//Map<String,Object> map = new HashMap<String,Object>();
			AuctionGoods ag = agService.selectByPrimaryKey(auctionGoodsId);
			Integer auctionId = ag.getAuctionId();
			if(null != auctionId){
				AuctionProfession ap = apService.selectByPrimaryKey(auctionId);
				if(!Check.integerEqual(userId, ap.getUserId())){
					return Result.failure(json, "您不是该场拍卖的创建人，无法进行修改", "auth_lack");
				}
			}
			Integer status = ag.getMainStatus();
			if(null != status && 2 == status){
				return Result.failure(json, "该拍品已流拍", "already_done");
			}else if(null != status && 3 == status){
				return Result.failure(json, "该拍品已被其他会员拍下", "already_deal");
			}
			
			if(null != countDown){
				Date date = new Date();
				Calendar cNow = Calendar.getInstance();
				cNow.add(Calendar.SECOND, -15);
				Date freshTime = cNow.getTime();
				AuctionGoods auctionGoods = new AuctionGoods();
				auctionGoods.setId(auctionGoodsId);
				auctionGoods.setUpdatedAt(date);
				auctionGoods.setUpdatedBy(user.getUsername());
				auctionGoods.setRefreshTime(freshTime);//倒计时的刷新时间
				agService.updateByPrimaryKeySelective(auctionGoods);
				long remainSeconds = calculateRemainSeconds(freshTime);
				json.put("remainSeconds", remainSeconds);
			}
		}catch (Exception e) {
			Result.catchError(e, logger, this.getClass().getName()+"/ap/hall/", json);
		}
		return Result.success(json);
	}*/
	
	private long calculateRemainSeconds(Date d){
		long remainSeconds = 120;
		if(null != d){
			Calendar cNow = Calendar.getInstance();
			Calendar c = Calendar.getInstance();
			c.setTime(d);
			long millisecond = cNow.getTimeInMillis() - c.getTimeInMillis();
			long second = millisecond/1000;
			remainSeconds = 120 - second;
			//System.out.println(remainSeconds);
			if(remainSeconds < 0 || remainSeconds > 120){
				remainSeconds = 120;
			}
		}
		//System.out.println(remainSeconds);
		return remainSeconds;
	}
	
	@ResponseBody
	@RequestMapping(value="/getRemainSeconds", method=RequestMethod.POST)
	public JSONObject getRemainSeconds(HttpServletRequest request, @RequestParam Integer auctionGoodsId){
		JSONObject json = new JSONObject();
		try {
			BaseUser user = ActionUtil.checkSession4User(request.getSession());//验证session中的user，存在即返回
			if(null == user){
				return Result.userSessionInvalid(json);//返回session过期的json提示
			}
			AuctionGoods ag = agService.selectByPrimaryKey(auctionGoodsId);
			Integer status = ag.getMainStatus();
			if(null != status && 2 == status){
				json.put("agStatus", "already_done");
			}else if(null != status && 3 == status){
				json.put("agStatus", "already_deal");
			}
			long remainSeconds = calculateRemainSeconds(ag.getRefreshTime());
			json.put("remainSeconds", remainSeconds);
			
			Map<String, Object> map = new HashMap<String, Object>();
			//TODO 更新拍场在线人数，同一用户只更新updated_at,通过该字段判断在线人数
			Integer auctionId = ag.getAuctionId();
			Integer userId = user.getId();
			Date date = new Date();
		 	map.put("auctionId", auctionId);
		 	map.put("auctionType", 1);//专场
		 	map.put("userId", userId);
		 	List<AuctionUser> auList = auService.selectListByCondition(map);
		 	if(Check.isNotNull(auList)){
		 		AuctionUser au = auList.get(0);
		 		au.setUpdatedAt(date);
		 		auService.updateByPrimaryKey(au);
		 	}else{
		 		AuctionUser au = new AuctionUser();
		 		au.setUpdatedAt(date);
		 		au.setAuctionId(auctionId);
		 		au.setAuctionType(1);
		 		au.setUserId(userId);
		 		au.setUsername(user.getUsername());
		 		au.setMainStatus(1);
		 		auService.insertSelective(au);
		 	}
		 	
		 	map.clear();
		 	map.put("auctionId", ag.getAuctionId());
		 	map.put("auctionType", 1);//专场
		 	map.put("showRecentUserCount", 1);
			int userCount = auService.selectCountByCondition(map);
			json.put("userCount", userCount);
		}catch (Exception e) {
			Result.catchError(e, logger, this.getClass().getName()+"/ap/hall/getRemainSeconds", json);
		}
		return Result.success(json);
	}
	
	@ResponseBody
	@RequestMapping(value="/setRemainSeconds", method=RequestMethod.POST)
	public JSONObject setRemainSeconds(HttpServletRequest request, 
			@RequestParam(required=false) Integer forceOver,
			@RequestParam Integer auctionGoodsId){
		JSONObject json = new JSONObject();
		try {
			BaseUser user = ActionUtil.checkSession4User(request.getSession());//验证session中的user，存在即返回
			if(null == user){
				return Result.userSessionInvalid(json);//返回session过期的json提示
			}
			AuctionGoods ag = agService.selectByPrimaryKey(auctionGoodsId);
			Integer auctionId = ag.getAuctionId();
			if(null != auctionId){
				AuctionProfession ap = apService.selectByPrimaryKey(auctionId);
				int apId = ap.getUserId();
				int userId = user.getId();
				if(apId == userId && (null != ap.getHaveBegun() && 1 != ap.getHaveBegun())){//只有该次拍卖的管理员才能修改,预展中不能修改
					AuctionGoods newAg = new AuctionGoods();
					Calendar now = Calendar.getInstance();
					if(null != forceOver){
						now.add(Calendar.SECOND, -120);//最长时间是120秒，则剩余0秒
						newAg.setMainStatus(2);//流拍
					}else{
						now.add(Calendar.SECOND, -105);//最长时间是120秒，则剩余15秒
					}
					newAg.setId(ag.getId());
					newAg.setRefreshTime(now.getTime());
					agService.updateByPrimaryKeySelective(newAg);//更新倒计时
					json.put("remainSeconds", 15);
				}
			}
		}catch (Exception e) {
			Result.catchError(e, logger, this.getClass().getName()+"/ap/hall/setRemainSeconds", json);
		}
		return Result.success(json);
	}
	
	@ResponseBody
	@RequestMapping(value="/getProfessionHaveBegun", method=RequestMethod.POST)
	public JSONObject getProfessionHaveBegun(HttpServletRequest request,
			@RequestParam Integer auctionId) {
		JSONObject json = new JSONObject();
		try {
			//Map<String, Object> map = ActionUtil.getAllParam(request);
			AuctionProfession ap = apService.selectByPrimaryKey(auctionId);
			Integer haveBegun = ap.getHaveBegun();
			if(null == haveBegun)haveBegun = 1;
			json.put("haveBegun", haveBegun);
		} catch (Exception e) {
			Result.catchError(e, logger, this.getClass().getName()+"/ap/getProfessionHaveBegun", json);
		}
		return Result.success(json);
	}
	
}
